package com.mjh.zhujianju.service.agency.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.model.SysUser;
import com.livew.framework.base.service.FileService;
import com.livew.framework.base.service.impl.BaseServiceImpl;
import com.livew.framework.enums.EStatus;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.page.PagedBeanUtil;
import com.livew.framework.page.PagedResult;
import com.livew.framework.pojo.LoginUserInfo;
import com.livew.framework.sql.XTSqlUtils;
import com.livew.framework.utils.XTCurrentUser;
import com.livew.framework.utils.XTEntityUtils;
import com.livew.framework.utils.XTListUtils;
import com.mjh.zhujianju.dao.agency.WorkDynamicMapper;
import com.mjh.zhujianju.enums.BusinessEnum;
import com.mjh.zhujianju.model.agency.DepartmentEO;
import com.mjh.zhujianju.model.agency.WorkDynamicEO;
import com.mjh.zhujianju.model.base.ContentEO;
import com.mjh.zhujianju.service.agency.DepartmentService;
import com.mjh.zhujianju.service.agency.DeptUserService;
import com.mjh.zhujianju.service.agency.WorkDynamicService;
import com.mjh.zhujianju.service.base.CommentService;
import com.mjh.zhujianju.service.base.ContentService;
import com.mjh.zhujianju.service.base.HitsService;
import com.mjh.zhujianju.service.base.PraiseService;
import com.mjh.zhujianju.util.FileUrlAdapter;
import com.mjh.zhujianju.util.HTMLSpirit;
import com.mjh.zhujianju.vo.agency.DepartmentVO;
import com.mjh.zhujianju.vo.agency.WorkDynamicVO;
import com.mjh.zhujianju.vo.base.CommentVO;

/**
 * @author liuyang
 * @Description: 动态
 * @date 2018/8/9 22:43
 */
@Service
public class WorkDynamicServiceImpl extends BaseServiceImpl<WorkDynamicEO> implements WorkDynamicService {

    @Autowired
    private WorkDynamicMapper workDynamicMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private PraiseService praiseService;

    @Autowired
    private ContentService contentService;
    
    @Autowired
    private CommentService commentService;

    @Autowired
    private DeptUserService deptUserService;
    
    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private HitsService hitsService;

    public WorkDynamicServiceImpl(WorkDynamicMapper workDynamicMapper) {
        super(workDynamicMapper);
    }

    @Override
    public List<WorkDynamicVO> queryWorkDynamicIndex() {
        List<WorkDynamicVO> list = Lists.newArrayList();
        WorkDynamicVO workDynamicVO = workDynamicMapper.queryWorkDynamicNewOne();
        if (workDynamicVO == null){
            return list;
        }
        if(workDynamicVO.getDeptId()!=null) {
        	try {
        		DepartmentVO vo =	departmentService.getInfo(workDynamicVO.getDeptId());
        		if(vo!=null) {
        			workDynamicVO.setDeptName(vo.getName());
        			workDynamicVO.setRemark5(vo.getFileAction());
        		}
			} catch (XTBusinessException e) {
				e.printStackTrace();
			}
        }
        SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd");
        workDynamicVO.setRemark2(sdf1.format(workDynamicVO.getCreateTime()));
        //用户图片
        List<Long> userIds = fileService.getFileByCaseId(workDynamicVO.getCreateUserId(), SysUser.class.getName(),null);
        if (!CollectionUtils.isEmpty(userIds)){
            workDynamicVO.setFileAction(FileUrlAdapter.assemblyAction(userIds.get(0)));
        }

        Long businessId = workDynamicVO.getId();

        //动态图片
        List<Long> fileIds = fileService.getFileByCaseId(businessId,WorkDynamicEO.class.getName(),null);
        if (!CollectionUtils.isEmpty(fileIds)){
            workDynamicVO.setFileActions(FileUrlAdapter.assemblyAction(fileIds));
        }

        String type = BusinessEnum.TYPE_WORKDYNAMIC.getCode();
        //点赞数
        Integer praiseTotals = praiseService.qeruyPraiseTotals(type,businessId);
        workDynamicVO.setTotalPraise(praiseTotals);

        //评论数
        Integer totalComment = commentService.queryCommentTotal(type,businessId);
        workDynamicVO.setTotalComment(totalComment);
        list.add(workDynamicVO);

        return list;
    }

    @Override
    public List<WorkDynamicVO> queryWorkDynamicList(Long deptId) {
        List<Long> userids = Lists.newArrayList();
        if (deptId !=0){
            userids = deptUserService.queryDeptUserByDeptId(deptId);
        }
        DepartmentVO dept = null;    
        try {
        	dept = 	departmentService.getInfo(deptId);
		} catch (XTBusinessException e) {
			e.printStackTrace();
		}
        List<WorkDynamicVO> list = workDynamicMapper.queryWorkDynamicList(userids);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        //组装用户图片
        List<Long> userIds = list.stream().map(workDynamicVO -> workDynamicVO.getCreateUserId()).distinct().collect(Collectors.toList());
        List<FileEO> fileEOList = fileService.getFileByIds(userIds,SysUser.class.getName(),null);
        if (!CollectionUtils.isEmpty(fileEOList)){
            for(WorkDynamicVO vo : list){
            	if(dept!=null) {
            		vo.setDeptName(dept.getName());
            	}
                for (FileEO fileEO : fileEOList){
                    if (vo.getCreateUserId().equals(fileEO.getCaseId())){
                        vo.setFileAction(FileUrlAdapter.assemblyAction(fileEO.getId()));
                        continue;
                    }
                }
            }
        }

        //动态图片
        List<Long> businessIds = list.stream().map(workDynamicVO -> workDynamicVO.getId()).distinct().collect(Collectors.toList());
        List<FileEO> workFiles = fileService.getFileByIds(businessIds,WorkDynamicEO.class.getName(),null);
        if (!CollectionUtils.isEmpty(workFiles)){
            for(WorkDynamicVO vo : list){
                List<Long> fileIds = Lists.newArrayList();
                for (FileEO fileEO : workFiles){
                    if (vo.getId().equals(fileEO.getCaseId())){
                        fileIds.add(fileEO.getId());
                    }
                }
                vo.setFileActions(FileUrlAdapter.assemblyAction(fileIds));
            }
        }

        //统计
        String type = BusinessEnum.TYPE_WORKDYNAMIC.getCode();
        list.stream().forEach(workDynamicVO -> {
            //点赞数
            Integer praiseTotals = praiseService.qeruyPraiseTotals(type,workDynamicVO.getId());
            workDynamicVO.setTotalPraise(praiseTotals);

            //评论数
            Integer totalComment = commentService.queryCommentTotal(type,workDynamicVO.getId());
            workDynamicVO.setTotalComment(totalComment);
        });
        return list;
    }

    @Override
    public WorkDynamicVO queryWorkDynamicInfo(Long id) {
        //动态详情
        WorkDynamicVO workDynamicVO = workDynamicMapper.queryWorkDynamicInfo(id);
        if (workDynamicVO == null){
            return null;
        }

        List<FileEO> fileEOList = fileService.getFileById(workDynamicVO.getCreateUserId(),SysUser.class.getName(),null);
        if (!CollectionUtils.isEmpty(fileEOList)){
            workDynamicVO.setFileAction(FileUrlAdapter.assemblyAction(fileEOList.get(0).getId()));
        }

        List<FileEO> workFiles = fileService.getFileById(workDynamicVO.getId(),WorkDynamicEO.class.getName(),null);
        if (!CollectionUtils.isEmpty(workFiles)){
            List<Long> ids = workFiles.stream().map(fileEO -> fileEO.getId()).collect(Collectors.toList());
            workDynamicVO.setFileActions(FileUrlAdapter.assemblyAction(ids));
        }

        String type = BusinessEnum.TYPE_WORKDYNAMIC.getCode();

        //浏览量+1
        hitsService.updateNumber(type,id);

        //评论列表
        List<CommentVO> commentVOList = commentService.queryCommentList(type,id);
        if (!CollectionUtils.isEmpty(commentVOList)){
            workDynamicVO.setCommentList(commentVOList);
        }

        //评论数
        Integer totalComment = commentService.queryCommentTotal(type,workDynamicVO.getId());
        workDynamicVO.setTotalComment(totalComment);

        //点赞数
        Integer praiseTotals = praiseService.qeruyPraiseTotals(type,workDynamicVO.getId());
        workDynamicVO.setTotalPraise(praiseTotals);
        
        //阅读数量
        Long hitsTotal = hitsService.queryHitsTotal(type,id);
        workDynamicVO.setTotalHits(hitsTotal);
        
        return workDynamicVO;
    }

    @Override
	public void saveInfo(WorkDynamicVO vo) throws XTBusinessException {
		WorkDynamicEO eo = new WorkDynamicEO();
		BeanUtils.copyProperties(vo, eo);
		eo.setStatus(EStatus.active.getCode());
//		LoginUserInfo info = XTCurrentUser.getCurrentUser();
//		OrganizationEO org =	organizationService.get();
//		if(org!=null) {
//			eo.setDeptId(org.getId());
//		}
//		eo.setDeptId(info.getDeptId());
		this.save(eo);
		if (!XTListUtils.isEmpty(vo.getFileIds())) {
			fileService.updateList(vo.getFileIds(), eo.getId(), WorkDynamicEO.class.getName());
		}
//		if (vo.getContentEO().getContent() != null) {
//			contentService.saveOrUpdate(BusinessEnum.TYPE_WORKDYNAMIC.getCode(), eo.getId(), vo.getContentEO().getContent());
//		}
		
	}

	@Override
	public void updateInfo(WorkDynamicVO vo) throws XTBusinessException {
		WorkDynamicEO eo = new WorkDynamicEO();
		BeanUtils.copyProperties(vo, eo);
		LoginUserInfo info = XTCurrentUser.getCurrentUser();
		eo.setDeptId(info.getDeptId());
		eo.setStatus(EStatus.active.getCode());
		this.updateByPrimaryKeySelective(eo);
		if (XTListUtils.isEmpty(vo.getFileIds())) {
			fileService.updateList(vo.getFileIds(), eo.getId(), WorkDynamicEO.class.getName());
		}
		// 更新内容
//		contentService.saveOrUpdate(BusinessEnum.TYPE_WORKDYNAMIC.getCode(), eo.getId(), vo.getContentEO().getContent());
	}

	@Override
	public PagedResult<WorkDynamicVO> getVOPage(WorkDynamicVO vo) {
		Integer pageNo = vo.getPageNo() == null ? 1 : vo.getPageNo();
		Integer pageSize = vo.getPageSize() == null ? 15 : vo.getPageSize();
		PageHelper.startPage(pageNo, pageSize);
		if(vo.getTitle()!=null) {
			vo.setTitle(XTSqlUtils.replaceSeparator(vo.getTitle()));
		}
		List<WorkDynamicEO> list = workDynamicMapper.selectPagination(vo);
		PagedResult<WorkDynamicEO> page = PagedBeanUtil.toPagedResult(list);
		PagedResult<WorkDynamicVO> result = new PagedResult<>();
		BeanUtils.copyProperties(page, result);
		if (!XTListUtils.isEmpty(list)) {
			List<Long> ids = XTEntityUtils.getIdList(list);
			List<WorkDynamicVO> voList = new ArrayList<WorkDynamicVO>();
			Map<Long, FileEO> files = fileService.getMapTopOne(ids, WorkDynamicEO.class.getName(), null);
			List<Long> deptIds = new ArrayList<>();//部门ID
			for (WorkDynamicEO wd : list) {
				WorkDynamicVO d = new WorkDynamicVO();
				BeanUtils.copyProperties(wd, d);
				String ct =HTMLSpirit.delHTMLTag(wd.getTitle());
				wd.setTitle(ct);
				voList.add(d);
				FileEO file = files.get(d.getId());
				if (file != null) {
					d.getFiles().add(file);
				}
				deptIds.add(wd.getDeptId());
			}
			Map<Long, DepartmentEO>  deptMap =	departmentService.getMapByIdList(deptIds);
			if(deptMap!=null) {
				for (WorkDynamicVO wd : voList) {
					DepartmentEO dept =	deptMap.get(wd.getDeptId());
					if(dept!=null) {
						wd.setDeptName(dept.getName());
					}
				}	
			}
			result.setDataList(voList);
		}
		return result;
	}

	@Override
	public WorkDynamicVO getInfo(Long id) throws XTBusinessException{
		WorkDynamicEO wd = super.getByPrimaryKey(id);
		if (wd != null) {
			WorkDynamicVO vo = new WorkDynamicVO();
			BeanUtils.copyProperties(wd, vo);
			List<FileEO> files = fileService.getFileById(id, WorkDynamicEO.class.getName(), null);
			if(!XTListUtils.isEmpty(files)) {
				vo.setFiles(files);
		  		vo.setFileIds(XTEntityUtils.getIdList(files));
			}
			//部门
			DepartmentEO dept =	departmentService.getByPrimaryKey(wd.getDeptId());
			if(dept!=null) {
				vo.setDeptName(dept.getName());
			}
			return vo;
		}

		return null;
	}
    
   
}
